<?php
namespace App\Helpers\Encrypt;


class Aes extends BaseEncrypt implements Encrypt {

    private  $_key;
    private  $_iv;
    private $_token;
    private $mode = 'AES-128-CBC';


    public  function __construct($config=[]){
        if (!extension_loaded('openssl')){
            throw new MissingExtensionException('The OpenSSL PHP extension is required to use the FlowdockHandler');
        }
        $token = $config['token']?$config['token']:$this->getAppKey();
        $this->setKey($token);
    }

    public static function make($config=[])
    {
        return new static($config);
    }

    private function setKey($token)
    {
        $length = $this->keyLength();
        $this->_token = sha1($token);
        $this->_key =  substr($this->_token, 0, $length);
        $this->_iv = substr($this->_token,-$length,$length);
    }

    public function keyLength()
    {
        if(!in_array(strtolower($this->mode),openssl_get_cipher_methods())){
            die('加密方法不存在');
        }
        return openssl_cipher_iv_length($this->mode);
    }


    public function getParams(){
        return [
            'key'=>$this->_key,
            'iv'=>$this->_iv,
            'token'=>$this->_token,
            'mode'=>$this->mode
        ];
    }

    /**
     * 加密
     * @param string $str 要处理的字符串
     * @return string
     */
    public function encrypt($str) {
        $str=openssl_encrypt($str, $this->mode,$this->_key,OPENSSL_RAW_DATA,$this->_iv);
        $encrypt=base64_encode($str);
        return $encrypt;
    }

    /**
     * 解密
     * @param string $str 要处理的字符串
     * @return string
     */
    public function decrypt($str) {
        $str = $this->spaceRepeat($str);
        $str = base64_decode($str);
        $decrypt = openssl_decrypt($str, $this->mode, $this->_key, OPENSSL_RAW_DATA,$this->_iv);
        return $decrypt??$str;
    }

    public function spaceRepeat($str){
        $str = str_replace(' ', '+', $str); //替换全角空格为半角
        return $str;
    }

}